package com.lzx.httpclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;


public class FileBody extends AbstractBody {
	
	private File file;
	
	private String filename;
	
	private String name;
	
	private String charset;
	
	public FileBody(File file, String name) {
		this(file, name, "application/octet-stream", "utf-8");
	}
	
	public FileBody(File file, String name, String charset) {
		this(file, name, "application/octet-stream", charset);
	}
	
	public FileBody(File file, String name, String mimeType, String charset) {
		super(mimeType);
		this.file = file;
		this.name = name;
		filename = file.getName();
	}
		

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	
	
//	Content-Disposition: form-data; name="uploadFile"; filename="1.txt" 
//	Content-Type: text/plain
//	
//	file content LR
	@Override
	public void writeTo(OutputStream os, boolean writeContent) {
		try {
//			-----------------------------98942870323811 
//			Content-Disposition: form-data; name="uploadFile"; filename="a.txt" 
//			Content-Type: text/plain 
//			
//			22222222222222222222
			
			StringBuilder sb = new StringBuilder();
			sb.append("--" + this.boundary + LR);
			sb.append("Content-Disposition: form-data; name=\""+  this.name +"\"; filename=\""+ this.filename +"\"" + LR);
			sb.append("Content-Type: " + getMimeType() + LR);
			sb.append(LR);
			os.write(sb.toString().getBytes("utf-8"));
//			System.out.print(sb);
			
			if(writeContent) {
				byte[] b = new byte[1024];
				InputStream is = new FileInputStream(file);
				int i;
				while((i = is.read(b, 0 , b.length)) != -1) {
					os.write(b, 0, i);
				}
				os.flush();
				is.close();
			}
			os.write("\r\n".getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public long getContentLength() {
		return file.length();
	}
	
	
	
	
	
	
	

}
